package com.qmhl.toolposition.fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.bumptech.glide.Glide
import com.hjq.toast.Toaster
import com.lxj.xpopup.XPopup
import com.qmhl.toolposition.R
import com.qmhl.toolposition.activity.AddPositionActivity
import com.qmhl.toolposition.activity.BannerDetailActivity
import com.qmhl.toolposition.activity.OneKeyLoginActivity
import com.qmhl.toolposition.activity.SmoothBeforeActivity
import com.qmhl.toolposition.activity.SmoothMoveActivity
import com.qmhl.toolposition.activity.VipActivity
import com.qmhl.toolposition.adapter.CareAdapter
import com.qmhl.toolposition.api.UserService
import com.qmhl.toolposition.bean.CareBean
import com.qmhl.toolposition.bean.DataBean
import com.qmhl.toolposition.databinding.DialogDelFriendBinding
import com.qmhl.toolposition.databinding.FragmentAppHomeBinding
import com.qmhl.toolposition.databinding.PopupWinHomeSettingBinding
import com.qmhl.toolposition.enu.CatSmooth
import com.qmhl.toolposition.event.LoginEvent
import com.qmhl.toolposition.event.PositionEvent
import com.qmhl.toolposition.utils.PUtils
import com.qmhl.toolposition.utils.PreferenceUtil
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus


class AppHomeFragment : Fragment() {

    private lateinit var binding: FragmentAppHomeBinding
    private var careAdpter: CareAdapter = CareAdapter()
    private var currentPositionInfo = ""
    private lateinit var mLocationClient: AMapLocationClient

    private val handler: Handler = Handler()
    private val runnable = Runnable {
        // 在这里编写需要定时执行的任务代码
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAppHomeBinding.inflate(inflater, container, false)
        initData()
        initListener()
        return binding.root
    }


    private fun initListener() {

        binding.addPosition.setOnClickListener {
            startActivity(Intent(context, AddPositionActivity::class.java))
        }


        careAdpter.addOnItemChildClickListener(R.id.btn_setting) { adapter, view, position ->
            showPopupWindow(position)
        }
    }

    /**
     * 弹出设置 popupWindow
     * **/
    private fun showPopupWindow(position: Int) {
        val popupWindow = PopupWindow()

        val binding: PopupWinHomeSettingBinding = PopupWinHomeSettingBinding.inflate(layoutInflater)


        popupWindow.contentView = binding.root
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.isOutsideTouchable = true

        val mainActivity = LayoutInflater.from(context).inflate(R.layout.activity_main, null)
        popupWindow.showAtLocation(mainActivity, Gravity.BOTTOM, 0, 0)

        var layoutParams = activity?.window?.attributes
        layoutParams?.alpha = 0.5f

        activity?.window?.attributes = layoutParams

        popupWindow.setOnDismissListener {
            val layoutParams1 = activity?.window?.attributes
            layoutParams1?.alpha = 1.0f;
            activity?.window?.attributes = layoutParams1


        }

        val isLogin = PreferenceUtil.isLogin()
        //查看位置轨迹
        binding.llTrajectory.setOnClickListener {
            popupWindow.dismiss()
            if (isLogin) {
                val friend = careAdpter.items[position]
                var intent = Intent(context, SmoothBeforeActivity::class.java)
                intent.putExtra("type", CatSmooth.FRIEND.type)
                intent.putExtra("friendId", friend.friendId)
                intent.putExtra("nickname", friend.nickname)
                startActivity(intent)
            } else {
                EventBus.getDefault().postSticky(LoginEvent(0))
            }

        }

        //修改用户昵称
        binding.llModifyUsername.setOnClickListener {
            val friend = careAdpter.items[position]
            showModifyNicknameDialog(friend.friendId)
            popupWindow.dismiss()
        }

        //删除好友
        binding.llDel.setOnClickListener {
            val friend = careAdpter.items[position]
            showDelFriendDialog(friend.friendId)
            popupWindow.dismiss()
        }

        //取消popupWindow
        binding.btnCancel.setOnClickListener {
            popupWindow.dismiss()
        }

    }

    private fun showModifyNicknameDialog(friendId: Int) {


        XPopup.Builder(context)
            .asInputConfirm(
                "修改昵称",
                "请输入好友备注昵称"
            ) {
                modifyNicknameRequest(it, friendId)
            }
            .show()

    }

    private fun modifyNicknameRequest(nickname: String, friendId: Int) {
        lifecycleScope.launch {
            var content = UserService.create()
                .setNicename(nickname, friendId.toLong())
            if (content.code == 200) {
                getFriendList()
            } else {
                Toaster.showShort(content.msg)
            }

        }
    }

    private fun delFriendRequest(friendId: Int) {
        lifecycleScope.launch {
            var content = UserService.create()
                .delFriend(friendId.toLong())
            if (content.code == 200) {
                getFriendList()
            } else {
                Toaster.showShort(content.msg)
            }

        }
    }


    private fun showDelFriendDialog(friendId: Int) {
        XPopup.Builder(context)
            .asConfirm(
                "删除好友",
                "删除后，双方将不再共享位置和轨迹。"
            ) {
                delFriendRequest(friendId)
            }
            .show()

    }

    private fun initData() {
        getPositionInfo()
        setBanner()
        getFriendList()


        binding.refreshLayout.setOnRefreshListener { refresh ->
            getFriendList()
            refresh.finishRefresh(1000 /*,false*/) //传入false表示刷新失败
        }

    }

    private fun getFriendList() {

        lifecycleScope.launch {
            var content = UserService.create()
                .friendList()
            if (content.code == 200) {
                val data = content.data
                if (data.isNotEmpty()) {
                    binding.llCare.visibility = View.GONE
                    binding.refreshLayout.visibility = View.VISIBLE
                } else {
                    binding.llCare.visibility = View.VISIBLE
                    binding.refreshLayout.visibility = View.GONE
                }
                binding.rv.adapter = careAdpter

                careAdpter.submitList(data)
                val layoutManager = LinearLayoutManager(context)
                binding.rv.layoutManager = layoutManager


            }
        }


    }

    private fun getFriendDataList(): MutableList<CareBean>? {
        var list = mutableListOf<CareBean>()
        list.add(CareBean(currentPositionInfo, "我自己", "2023-12-25"))
        list.add(CareBean("广东省广州市花都区从化大道91号", "137****3678", "2023-12-25"))
        list.add(CareBean("广东省广州市番禺区化龙街62号", "136****3555", "2023-12-23"))
        list.add(CareBean("广东省佛山市顺德区伦教镇伦教市政府12号", "195****2229", "2023-12-25"))
        return list
    }

    private fun setBanner() {

        lifecycleScope.launch {
            var content = UserService.create()
                .getBanner()
            if (content.code == 200) {
                val data = content.data


                binding.mainBanner.setAdapter(object :
                    BannerImageAdapter<DataBean>(DataBean.convertBannerList(content)) {
                    override fun onBindView(
                        holder: BannerImageHolder, data: DataBean, position: Int, size: Int
                    ) {
                        Glide.with(holder.itemView).load(data.imageUrl)
                            .into(holder.imageView)
                    }
                }).addBannerLifecycleObserver(this@AppHomeFragment)
                    .setIndicator(CircleIndicator(this@AppHomeFragment.context))

            }
        }




        binding.mainBanner.setOnBannerListener { data, position ->
            startBannerDetailActivity(position)
        }
    }

    private fun startBannerDetailActivity(position: Int) {
        startActivity(Intent(context, BannerDetailActivity::class.java))
    }

    private fun getPositionInfo() {

        //声明AMapLocationClient类对象
        val mLocationOption = AMapLocationClientOption()
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.interval = 1000 * 60 * 3;


        //初始化定位
        mLocationClient = AMapLocationClient(context)
        mLocationClient.setLocationOption(mLocationOption)

        //设置定位回调监听
        mLocationClient.setLocationListener(AMapLocationListener {
            val code = it.errorCode
            var value = ""
            var latitude = 0.0
            var longitude = 0.0
            if (code == 0) {
                val address = it.address
                //纬度
                latitude = it.latitude
                //经度
                longitude = it.longitude
                val city = it.city
                value = "最后位置：$address"

            } else {
                value = "正在获取您的位置："

            }


            //这里可以判断下不用每次都去刷新布局
            if (!(value == currentPositionInfo)) {
                var dataList = getFriendDataList()
//                dataList?.set(0, CareBean(value, "我自己", "137****9899"))
//                careAdpter.submitList(dataList)
            }

            currentPositionInfo = value

            lifecycleScope.launch {
                var address = "正在获取您的位置："
                if (value != address) {
                    address = it.address
                }
                var content = UserService.create()
                    .savePoint(latitude.toString(), longitude.toString(), address)
                if (content.code == 200) {

                }
            }
            EventBus.getDefault().postSticky(PositionEvent(value, latitude, longitude))


        })

        mLocationClient.stopLocation()
        mLocationClient.startLocation()


    }


    private val NOTIFICATION_CHANNEL_NAME = "BackgroundLocation"
    private lateinit var notificationManager: NotificationManager
    var isCreateChannel = false

    @SuppressLint("NewApi")
    private fun buildNotification(): Notification? {
        var builder: Notification.Builder? = null
        var notification: Notification? = null
        if (Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏

            notificationManager =
                context?.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager

            val channelId = context?.packageName
            if (!isCreateChannel) {
                val notificationChannel = NotificationChannel(
                    channelId,
                    NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
                )
                notificationChannel.enableLights(true) //是否在桌面icon右上角展示小圆点
                notificationChannel.lightColor = Color.BLUE //小圆点颜色
                notificationChannel.setShowBadge(true) //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel)
                isCreateChannel = true
            }
            builder = Notification.Builder(context, channelId)
        } else {
            builder = Notification.Builder(context)
        }
        builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(PUtils.Config.NOTIFY_TITLE)
            .setContentText(PUtils.Config.NOTIFY_TEXT)
            .setWhen(System.currentTimeMillis())
        notification = if (Build.VERSION.SDK_INT >= 16) {
            builder.build()
        } else {
            return builder.notification
        }
        return notification
    }


    var notificationIsStart = true
    override fun onStart() {
        super.onStart()
        if (notificationIsStart) {
            notificationIsStart = false
            //启动后台定位，第一个参数为通知栏ID，建议整个APP使用一个
            mLocationClient.enableBackgroundLocation(2001, buildNotification());
        }

    }

    override fun onPause() {
        super.onPause()

    }


}





